package com.jbinfo.mongoot.controller;
import com.jbinfo.mongoot.operation.archive.Archive;
import com.jbinfo.mongoot.operation.archive.ArchiveRepository;
import com.jbinfo.mongoot.operation.visitor.Visitor;
import com.jbinfo.mongoot.util.PageModel;
import com.jbinfo.mongoot.util.XiMethodUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizard on 2017/3/31.
 */
@RestController
@RequestMapping("/archive")
@Api("fuzhou-archive类API")
public class ArchiveController {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ArchiveRepository archiveRepository;


    @ApiOperation("通过post请求添加archive信息")
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public Map<String, Object> add(@ModelAttribute Archive archive) {
        Map<String, Object> map = new HashMap();
        String description="";

        //验证参数是否为空
		if(archive.getCardid()==null ||  "".equals(archive.getCardid())){
			description+= "老人身份证号不能为空、";
		}
        if(archive.getCreated_by()==null ||  "".equals(archive.getCreated_by())){
            description+= "创建人不能为空、";
        }
        if(archive.getShequ_code()==null ||  "".equals(archive.getShequ_code())){
            description+= "社区不能为空";
        }
        if(archive.getComments()==null ||  "".equals(archive.getComments())){
            description+= "备注信息不能为空";
        }

        if("".equals(description)){//非空
            archive.setInvalid("1");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            archive.setCreated_date(simpleDateFormat.format(new Date()));
            Archive newArchive = archiveRepository.save(archive);
            map.put("archivedId", newArchive.getId());
            map.put("status", 1);
        }else{
            map.put("status", 0);
        }
        map.put("description", description);
        map.put("code", "");
        return map;
    }

    @ApiOperation("通过Id查询指定archive信息")
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public Map<String, Object> findByCardid(@RequestParam("id") String id) {
        Map<String, Object> map = new HashMap();
        Archive archive =  archiveRepository.findById(id);
        String description="";
        if (archive != null) {
            map.put("status", 1);
            map.put("result", archive);
        }else{
            description = "查询老人已不存在";
            map.put("status", 0);
        }
        map.put("description", description);
        map.put("code", "");
        return map;
    }

    @ApiOperation("通过Post请求修改指定archive信息")
    @RequestMapping(value = "/updateArchiveById", method = RequestMethod.POST)
    public Map<String, Object> updateByCardid(@ModelAttribute  Archive archive) throws ParseException {
        Map<String, Object> map = new HashMap();
        DBCollection collection = mongoTemplate.getCollection(mongoTemplate.getCollectionName(archive.getClass()));
        //唯一字段
        DBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(archive.getId()));
        //找到要修改的对象
        DBObject findOne = collection.findOne(query);
        //修改时间变更
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm;ss");
        archive.setUpdate_date(simpleDateFormat.format(new Date()));
        DBObject update = XiMethodUtil.method(archive,findOne);//要找其他字段原来的值，不然update会给你自动修改其他的值为null
        collection.update(query, update, false, true);//有的话修改，没有的话进行添加！第三个参数为true。
        map.put("status", 1);
        map.put("description", "");
        map.put("code", "");
        return map;
    }

    @ApiOperation("查询老人列表查询")
    @RequestMapping(value = "/findArchiveAll", method = RequestMethod.POST)
    public  PageModel<Archive> findALL(@ModelAttribute PageModel<Archive> page,
                                       @ModelAttribute Archive archive,
                                       @RequestParam(required = false) String sortFlag){
        Query query=new Query();
        Criteria criatira = new Criteria();
        Criteria criatira1 = new Criteria();
        Criteria criatira2 = new Criteria();
        Criteria criatira3 = new Criteria();
        Criteria criatira4 = new Criteria();
        Criteria criatira5 = new Criteria();
        Criteria criatira6 = new Criteria();
        Criteria criatira7 = new Criteria();
        Criteria criatira8 = new Criteria();
        Criteria criatira9 = Criteria.where("invalid").is("1");
        if(!StringUtils.isEmpty(archive.getName())){
            criatira1 = Criteria.where("name").regex(".*?" +archive.getName()+ ".*");
        }
        if(!StringUtils.isEmpty(archive.getCardid())){
            criatira2 = Criteria.where("cardid").regex(".*?" +archive.getCardid()+ ".*");
        }
        if(!StringUtils.isEmpty(archive.getCompany_name())){
            criatira3 = Criteria.where("company_name").is(archive.getCompany_name());
        }
        if(!StringUtils.isEmpty(archive.getAddress())){
            criatira4 = Criteria.where("address").regex(".*?" +archive.getAddress()+ ".*");
        }
        if(!StringUtils.isEmpty(archive.getPhone())){
            criatira5 = Criteria.where("phone").regex(".*?" +archive.getPhone()+ ".*");
        }
        if(!StringUtils.isEmpty(archive.getPlantime())){
            criatira6 = Criteria.where("plantime").gt(archive.getPlantime());
        }
        if(!StringUtils.isEmpty(archive.getResttime())){
            criatira7 = Criteria.where("resttime").gt(archive.getResttime());
        }
        if(!StringUtils.isEmpty(archive.getCompany_code())){
            criatira7 = Criteria.where("company_code").is(archive.getCompany_code());
        }
        criatira.andOperator(criatira1,criatira2,criatira3,criatira4,criatira5,criatira6,criatira7,criatira8,criatira9);
        query.addCriteria(criatira);

        //查询总数
        int count=(int) mongoTemplate.count(query,Archive.class);
        page.setTotal(count);

        //排序
        if("desc".equals(sortFlag)){
            query.with(new Sort(Sort.Direction.DESC, "resttime"));
        }else {
            query.with(new Sort(Sort.Direction.ASC, "resttime"));
        }
        int skip = (page.getPageNumber()-1)*page.getPageSize();
        query.skip(skip).limit(page.getPageSize());
        List<Archive> archiveList = mongoTemplate.find(query,Archive.class);

        page.setRows(archiveList);
        return page;
    }


    @ApiOperation("根据id删除师傅")
    @RequestMapping(value = "/removeById", method = RequestMethod.GET)
    public Map<String, Object> removeById(@RequestParam("id") String id) {
        mongoTemplate.updateMulti(new Query(new Criteria("id").is(id)), new Update().set("invalid", "0"),Archive.class);
        Map<String, Object> map = new HashMap();
        if(StringUtils.isEmpty(id)){
            map.put("status", 0);
        }else{
            map.put("status", 1);
        }
        map.put("description", "");
        map.put("code", "");
        return map;
    }

    @ApiOperation("根据服务组织编码查询师傅")
    @RequestMapping(value = "/findArchiveByCompanyCode", method = RequestMethod.GET)
    public  List<Archive> findArchiveByCompanyCode(@RequestParam("company_code") String company_code) {
        Query query = new Query();
        query.addCriteria(Criteria.where("company_code").is(company_code));
        List<Archive> archiveList =  mongoTemplate.find(query, Archive.class);
        return archiveList;
    }







}


